package com.micro.school.order.controller;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.micro.school.common.core.constant.Constants;
import com.micro.school.common.core.constant.PayConstants;
import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.core.utils.poi.ExcelUtil;
import com.micro.school.common.core.web.controller.BaseController;
import com.micro.school.common.core.web.domain.AjaxResult;
import com.micro.school.common.core.web.page.TableDataInfo;
import com.micro.school.common.log.annotation.Log;
import com.micro.school.common.log.enums.BusinessType;
import com.micro.school.common.security.utils.SecurityUtils;
import com.micro.school.order.entity.PayFeeItemConfig;
import com.micro.school.order.service.IPayFeeItemConfigService;
import com.micro.school.system.api.RemoteUserService;
import com.micro.school.system.api.domain.vo.MerMerchantVos;
import com.micro.school.system.api.domain.vo.PayFeeItemConfigVos;
import com.micro.school.system.api.model.LoginUser;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 收费项目配置Controller
 * 
 * @author lyb
 * @date 2025-08-14
 */
@RestController
@RequestMapping("/pay/payFeeItemConfig")
public class PayFeeItemConfigController extends BaseController
{
    @Autowired
    private IPayFeeItemConfigService payFeeItemConfigService;


    @Resource
    private RemoteUserService userService;

    /**
     * 查询收费项目配置列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PayFeeItemConfig payFeeItemConfig)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
//        if (!SecurityContextHolder.getUserName().contains("admin")) {
//            payFeeItemConfig.setCampusId(Integer.valueOf(SecurityContextHolder.getUserCompusId()));
//        }
        payFeeItemConfig.setTenantId(loginUser.getSysUser().getTenantId().intValue());
        List<PayFeeItemConfig> list = payFeeItemConfigService.selectPayFeeItemConfigList(payFeeItemConfig);
        return getDataTable(list);
    }

    /**
     * 查询收费项目配置列表
     */
    @GetMapping("/getList")
    public AjaxResult getList(PayFeeItemConfig payFeeItemConfig)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
//        if (!SecurityContextHolder.getUserName().contains("admin")) {
//            payFeeItemConfig.setCampusId(Integer.valueOf(SecurityContextHolder.getUserCompusId()));
//        }
        payFeeItemConfig.setTenantId(loginUser.getSysUser().getTenantId().intValue());
        payFeeItemConfig.setCloseStatus(PayConstants.YESORNO_Y);
        List<PayFeeItemConfig> list = payFeeItemConfigService.selectPayFeeItemConfigList(payFeeItemConfig);
        if(null!=list && !list.isEmpty()){
            list.sort(Comparator.comparing(PayFeeItemConfig::getOrderNum));
        }
        return AjaxResult.success(list);
    }
    /**
     * 导出收费项目配置列表
     */
    @Log(title = "收费项目配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PayFeeItemConfig payFeeItemConfig)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
//        if (!SecurityContextHolder.getUserName().contains("admin")) {
//            payFeeItemConfig.setCampusId(Integer.valueOf(SecurityContextHolder.getUserCompusId()));
//        }
        payFeeItemConfig.setTenantId(loginUser.getSysUser().getTenantId().intValue());
        List<PayFeeItemConfig> list = payFeeItemConfigService.selectPayFeeItemConfigList(payFeeItemConfig);
        ExcelUtil<PayFeeItemConfig> util = new ExcelUtil<PayFeeItemConfig>(PayFeeItemConfig.class);
        util.exportExcel(response, list, "收费项目配置数据");
    }

    @PostMapping("/selectMerchantByConfigId")
    public PayFeeItemConfigVos selectMerchantByConfigId(@RequestBody PayFeeItemConfigVos payFeeItemConfigVos){
        return payFeeItemConfigService.selectMerchantByConfigId(payFeeItemConfigVos);

    }

    /**
     * 获取收费项目配置详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        PayFeeItemConfig feeItemConfig = payFeeItemConfigService.selectPayFeeItemConfigById(id);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(feeItemConfig.getTenantId().intValue()!=loginUser.getTenantId()){
            return AjaxResult.error("租户不正确");
        }
        return success(feeItemConfig);
    }

    /**
     * 新增收费项目配置
     */
    @Log(title = "收费项目配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PayFeeItemConfig payFeeItemConfig)
    {

        LoginUser loginUser = SecurityUtils.getLoginUser();
//        if (!SecurityContextHolder.getUserName().contains("admin")) {
//            payFeeItemConfig.setCampusId(Integer.valueOf(SecurityContextHolder.getUserCompusId()));
//        }
        payFeeItemConfig.setTenantId(loginUser.getSysUser().getTenantId().intValue());
        payFeeItemConfig.setCreateTime(new Date());
        payFeeItemConfig.setCreateDept(loginUser.getSysUser().getDeptId());
        payFeeItemConfig.setCreateBy(loginUser.getUserid().toString());
        payFeeItemConfig.setUpdateBy(loginUser.getUserid().toString());
        payFeeItemConfig.setCreateTime(new Date());
        payFeeItemConfig.setUpdateTime(new Date());
        AjaxResult validAdd = validAdd(payFeeItemConfig);
        if(null!=validAdd){
            return validAdd;
        }
        setMerchantName(payFeeItemConfig);
        return toAjax(payFeeItemConfigService.insertPayFeeItemConfig(payFeeItemConfig));
    }
    private AjaxResult validAdd(PayFeeItemConfig payFeeItemConfig){
        //校验名字重复
        Map<Long,PayFeeItemConfig> itemConfigMap = payFeeItemConfigService.queryToMap(payFeeItemConfig.getTenantId());
        if(null!=itemConfigMap){
            for(Long key:itemConfigMap.keySet()){
                PayFeeItemConfig itemConfig = itemConfigMap.get(key);
                if(null!=itemConfig && itemConfig.getItemName().equals(payFeeItemConfig.getItemName())){
                    return AjaxResult.error("存在重名的收费项目，请重新输入");
                }
            }
        }
        return null;
    }
    private AjaxResult validUp(PayFeeItemConfig payFeeItemConfig){
        //校验名字重复
        Map<Long,PayFeeItemConfig> itemConfigMap = payFeeItemConfigService.queryToMap(payFeeItemConfig.getTenantId());
        if(null!=itemConfigMap){
            for(Long key:itemConfigMap.keySet()){
                PayFeeItemConfig itemConfig = itemConfigMap.get(key);
                if(null!=itemConfig && itemConfig.getItemName().equals(payFeeItemConfig.getItemName()) && !itemConfig.getId().equals(payFeeItemConfig.getId())){
                    return AjaxResult.error("存在重名的收费项目，请重新输入");
                }
            }
        }
        return null;
    }

    /**
     * 修改收费项目配置
     */
    @Log(title = "收费项目配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PayFeeItemConfig payFeeItemConfig)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payFeeItemConfig.setTenantId(loginUser.getSysUser().getTenantId().intValue());
        payFeeItemConfig.setUpdateBy(loginUser.getUserid().toString());
        payFeeItemConfig.setUpdateTime(new Date());
        AjaxResult validUp = validUp(payFeeItemConfig);
        if(null!=validUp){
            return validUp;
        }
        setMerchantName(payFeeItemConfig);
        payFeeItemConfigService.updatePayFeeItemConfig(payFeeItemConfig);
        return AjaxResult.success();
    }

    private void setMerchantName(PayFeeItemConfig payFeeItemConfig){
        if(null!=payFeeItemConfig.getMerchantPkId()){
            R<MerMerchantVos> merMerchantVosR = userService.queryMerMerchantById(payFeeItemConfig.getMerchantPkId());
            MerMerchantVos merMerchant = null;
            if(null!=merMerchantVosR && null!=merMerchantVosR.getData()){
                merMerchant = merMerchantVosR.getData();
            }
            if(null!=merMerchant){
                payFeeItemConfig.setMerchantName(merMerchant.getMerchantName());
            }
        }
    }

    /**
     * 删除收费项目配置
     */
    @Log(title = "收费项目配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        for(Long id:ids){
            PayFeeItemConfig itemQuery = payFeeItemConfigService.selectPayFeeItemConfigById(id);
            if(itemQuery.getTenantId().intValue() != loginUser.getTenantId().intValue()){
                return AjaxResult.error();
            }
        }
        return toAjax(payFeeItemConfigService.deletePayFeeItemConfigByIds(ids));
    }

    /**
     * 打开
     */
    @PostMapping(value = "/open/{id}")
    public AjaxResult open(@PathVariable("id") Long id)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        PayFeeItemConfig configUpdate = new PayFeeItemConfig();
        configUpdate.setCloseStatus(PayConstants.YESORNO_Y);
        configUpdate.setId(id.intValue());
        configUpdate.setTenantId(loginUser.getSysUser().getTenantId().intValue());
        configUpdate.setUpdateBy(loginUser.getUsername());
        configUpdate.setUpdateTime(new Date());
        if (payFeeItemConfigService.updatePayFeeItemConfig(configUpdate) == 0){
            return AjaxResult.error("修改失败,已生成过订单，无法修改");
        }
        return AjaxResult.success();
    }

    /**
     * 关闭
     */
    @PostMapping(value = "/close/{id}")
    public AjaxResult close(@PathVariable("id") Long id)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        PayFeeItemConfig configUpdate = new PayFeeItemConfig();
        configUpdate.setCloseStatus(PayConstants.YESORNO_N);
        configUpdate.setTenantId(loginUser.getSysUser().getTenantId().intValue());
        configUpdate.setId(id.intValue());
        configUpdate.setUpdateBy(loginUser.getUsername());
        configUpdate.setUpdateTime(new Date());
        if (payFeeItemConfigService.updatePayFeeItemConfig(configUpdate) == 0){
            return AjaxResult.error("修改失败,已生成过订单，无法修改");
        }
        return AjaxResult.success();
    }
}
